package com.learning.cloud2020.loadbalancer.impl;

import com.learning.cloud2020.loadbalancer.Loadbalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class CustomerLoadbalancer implements Loadbalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public int getAndIncrement() {
        int current ;
        int next;
        do{
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (atomicInteger.compareAndSet(current, next));

        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int next = getAndIncrement();
        int index = next % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
